import type { UserInfoData, UserInfoResponse } from '@/api/types/auth-responses'
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  getUserInfo,
} from '@/api/auth'

// 初始化状态 - 嵌套结构
const userInfoDataState: UserInfoData = {
  id: '',
  username: '',
  realname: '',
  avatar: null,
  birthday: null,
  sex: null,
  email: null,
  phone: '',
  status: 0,
  idCard: null,
  employee: {
    id: '',
    employeeNum: '',
    realname: '',
    phone: '',
    email: '',
    avatar: '',
    sysPositionCode: '',
    // 其他必要字段设置默认值
    createBy: '',
    createName: '',
    createTime: '',
    updateBy: '',
    updateName: '',
    updateTime: '',
    sysCompanyCode: null,
    sysOrgCode: '',
    delFlag: 0,
    tenantId: '',
    tenantName: null,
    abbreviation: null,
    positionStatus: '',
    sex: 0,
    userId: '',
    cardNumber: null,
    birthday: null,
    nativePlace: '',
    nation: null,
    idCardType: '',
    idCardNum: '',
    entryDate: null,
    maritalStatus: '',
    accountProperties: null,
    education: '',
    province: null,
    city: null,
    district: null,
    domicile: null,
    graduateSchool: null,
    professional: '',
    grade: null,
    businessUnits: null,
    contractType: null,
    contractNum: null,
    contractStartTime: null,
    contractEndTime: null,
    award: null,
    qualification: null,
    address: '',
    remark: '',
    workNo: '',
    isAdmin: '0',
    isDefaultLogin: null,
    picture: null,
    departIds: null,
    orgCodes: null,
    departNames: null,
    roleIds: null,
    roleNames: null,
    sysInstitutionCode: null,
    politicalOutlookCode: '',
    jobTitleCode: '',
    jobTitleName: null,
    mnemonicCode: '',
    titleCode: '',
    titleName: null,
    enterpriseEmail: '',
    landlinePhone: null,
    departmentHeadId: null,
    departmentHeadName: null,
    directSuperiorId: null,
    directSuperiorName: null,
    type: '',
    bank: '',
    accountNo: '',
    departIdList: null,
    departNameAbbr: null,
    status: 0,
    statusDesc: '',
  },
  sysTenant: {
    id: '',
    name: '',
    abbreviation: '',
    // 其他必要字段设置默认值
    createBy: '',
    createName: '',
    createTime: '',
    updateBy: '',
    updateName: '',
    updateTime: '',
    sysCompanyCode: null,
    sysOrgCode: '',
    delFlag: 0,
    status: 0,
    logo: null,
    contact: '',
    contactTel: '',
    contactEmail: null,
    address: '',
    endDate: null,
    beginDate: '',
    province: null,
    city: null,
    district: null,
    area: null,
    initDataStatus: 0,
    seal: null,
    no: '',
    domainName: null,
    industryCode: null,
    industryName: null,
    websiteName: null,
    description: null,
    priority: 0,
    legal: null,
    taxCode: null,
    bank: null,
    accountNo: null,
    parentId: null,
    sonTenantList: null,
    operateType: 0,
    code: '',
    userList: null,
    username: '',
    password: null,
    phone: '',
  },
  sysDepart: {
    id: '',
    departName: '',
    // 其他必要字段设置默认值
    parentId: '',
    departNameEn: null,
    departNameAbbr: '',
    departOrder: 0,
    description: null,
    orgCategory: '',
    orgType: '',
    orgCode: '',
    mobile: '',
    fax: null,
    legalPerson: null,
    taxId: '',
    accountNum: '',
    depositBank: '',
    directorUserIds: '',
    directorUserRealnames: '',
    address: '',
    memo: '',
    status: 0,
    qywxIdentifier: null,
    tenantId: '',
    treePath: null,
    oldDirectorUserIds: null,
    createBy: '',
    createTime: '',
    updateBy: '',
    updateTime: '',
    sysOrgCode: '',
    delFlag: 0,
    children: [],
    key: null,
    value: null,
  },
  deptIds: null,
  institutionId: '',
  sysCompanyCode: '',
}

const userInfoState: UserInfoResponse = {
  userInfo: { ...userInfoDataState },
}

export const useUserStore = defineStore(
  'user',
  () => {
    // 定义用户信息
    const userInfo = ref<UserInfoResponse>({ ...userInfoState })
    // 设置用户信息
    const setUserInfo = (val: UserInfoData | UserInfoResponse) => {
      console.log('设置用户信息', val)

      // 处理两种可能的输入格式：完整的UserInfoResponse或仅UserInfoData
      let userInfoData: UserInfoData
      let avatarPath: string = userInfoState.userInfo.avatar || '/static/images/default-avatar.png'

      if ('userInfo' in val) {
        // 如果是完整的UserInfoResponse
        userInfoData = val.userInfo
        avatarPath = val.userInfo.avatar || avatarPath
      }
      else {
        // 如果是UserInfoData
        userInfoData = val
        // 如果用户信息中有头像，则使用用户信息的头像
        if (userInfoData.avatar) {
          avatarPath = userInfoData.avatar
        }
      }

      userInfo.value = {
        userInfo: userInfoData,
      }
    }
    const setUserAvatar = (avatar: string) => {
      // 若头像为空 则使用默认头像
      userInfo.value.userInfo.avatar = avatar || userInfoState.userInfo.avatar
    }
    // 删除用户信息
    const clearUserInfo = () => {
      userInfo.value = { ...userInfoState }
      uni.removeStorageSync('user')
    }

    /**
     * 获取用户信息
     * 注意：通常情况下，我们直接从登录响应中获取用户信息
     * 这个方法保留以便在需要刷新用户信息时使用
     */
    const fetchUserInfo = async () => {
      try {
        const res = await getUserInfo()
        setUserInfo(res.data.userInfo)
        return res
      }
      catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    }

    return {
      userInfo,
      clearUserInfo,
      fetchUserInfo,
      setUserInfo,
      setUserAvatar,
    }
  },
  {
    persist: true,
  },
)
